package com.lightboat.web.controller.wx;

import com.lightboat.common.annotation.Anonymous;
import com.lightboat.common.constant.CacheConstants;
import com.lightboat.common.exception.ServiceException;
import com.lightboat.common.utils.RedisUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Lazy
@RestController
@RequiredArgsConstructor
@Tag(name = "小程序-MP：微信公众号")
@RequestMapping("/api/mp")
public class WxMpController {

    private final WxMpService wxService;

    @GetMapping("/getJsapiTicket")
    public String getJsapiTicket(@RequestParam String appid) throws WxErrorException {
        final WxJsapiSignature jsapiSignature = this.wxService.switchoverTo(appid).createJsapiSignature("111");
        System.out.println(jsapiSignature);
        return this.wxService.getJsapiTicket(true);
    }

    @Anonymous
    @Operation(summary = "CODE换取用户信息")
    @GetMapping("/greet")
    public ResponseEntity<WxOAuth2AccessToken> greetUser(@RequestParam String appid, @RequestParam String code, @RequestParam String state) {

        log.info("appid: {}, code: {}, state: {}", appid, code, state);

        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        try {
            WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code);
            log.debug("code 换取 accessToken {}", accessToken);
            RedisUtils.builder().set(CacheConstants.WX_TOKEN_CACHE + accessToken.getOpenId(), accessToken, accessToken.getExpiresIn() - 60);
            return ResponseEntity.<WxOAuth2AccessToken>ok(accessToken);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            throw new ServiceException(e.getError().getErrorMsg());
        }
    }
}
